package com.wm.controller;

import com.github.pagehelper.PageInfo;
import com.wm.entity.RbacUser;
import com.wm.entity.ResponseResult;
import com.wm.service.UserService;
import com.wm.util.Audience;
import com.wm.util.JwtUtil;
import com.wm.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private Audience audience;

    @PostMapping("/add")
    public ResponseResult<Void> addUser(@RequestBody  UserVo userVo){
        userService.add(userVo.getRbacUser(),userVo.getPermIds());
        return ResponseResult.SUCCESS;
    }

    @PostMapping("/findAll")
    public ResponseResult<PageInfo<RbacUser>> findAllUser(@PathVariable int pageNum){

        return new ResponseResult<>(userService.getByCondition(pageNum,null));
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseResult login(@RequestBody RbacUser user) {
        RbacUser u = userService.login(user.getAccount());
        if (u == null) {
            return new ResponseResult(501, "no account");
        }
        if (u.getPassword().equals(user.getPassword())) {

            //产生一个能表示用户唯一性的字符串，将其带回到客户端

            String jwt = JwtUtil.createJwt(u.getId(), u.getAccount(), audience);
            return new ResponseResult(jwt);
        } else {
            return new ResponseResult(502, "invalid password");
        }
    }

        @GetMapping("test")
        public ResponseResult test(@RequestHeader("token") String token) {
            log.debug("token:{}", token);
            //解析出来id或account
            return ResponseResult.SUCCESS;
        }

}
